<?php
namespace App\Module\User\Controller;

use App\Common\Controller\AbstractController;
use App\Component\Wechat\WechatFactory;
use App\Constants\Constant;
use App\Exception\AppException;
use App\Module\User\Request\Login\LoginRequest;
use App\Module\User\Service\UserService;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class LoginController extends AbstractController{

    /**
     * @Inject()
     * @var WechatFactory $wechatFactory
     */
    private $wechatFactory;

    /**
     * @Inject()
     * @var AuthManager $authManager
     */
    private $authManager;

    /**
     * @Inject()
     * @var UserService $userService
     */
    private $userService;

    public function wechat(LoginRequest $request){
        $result = $this->wechatFactory->getMiniProgram()->auth->session($request->input("code"));
        if(isset($result['errcode']) && $result['errcode'] != 0){
            throw new AppException($result['errmsg']);
        }
        $user = $this->userService->getByCredential($result['openid'],Constant::WECHAT);
        if(!$user){
            $wechat_info = $this->wechatFactory->getMiniProgram()->encryptor->decryptData($result['session_key'],$request->input("iv"),$request->input("encrypted_data"));
            $user = $this->userService->createByWechat($wechat_info);
        }

        return $this->response->json(['user_id'=>$user->user_id,'token'=>$this->authManager->guard(Constant::USER)->login($user)]);
    }
}